from datetime import datetime
from app import db
import json


class PaymentConfig(db.Model):
    """支付配置模型"""
    __tablename__ = 'payment_configs'
    
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False, comment='配置名称')
    payment_method = db.Column(db.String(20), nullable=False, comment='支付方式: wechat, alipay')
    is_enabled = db.Column(db.Boolean, default=True, comment='是否启用')
    
    # 微信支付配置
    wechat_app_id = db.Column(db.String(100), comment='微信应用ID')
    wechat_mch_id = db.Column(db.String(100), comment='微信商户号')
    wechat_api_key = db.Column(db.String(256), comment='微信API密钥')
    wechat_cert_path = db.Column(db.String(255), comment='微信证书路径')
    wechat_key_path = db.Column(db.String(255), comment='微信私钥路径')
    wechat_notify_url = db.Column(db.String(255), comment='微信支付回调地址')
    
    # 支付宝配置（预留）
    alipay_app_id = db.Column(db.String(100), comment='支付宝应用ID')
    alipay_private_key = db.Column(db.Text, comment='支付宝私钥')
    alipay_public_key = db.Column(db.Text, comment='支付宝公钥')
    alipay_notify_url = db.Column(db.String(255), comment='支付宝回调地址')
    
    # 通用配置
    timeout_seconds = db.Column(db.Integer, default=1800, comment='支付超时时间(秒)')
    max_retry_times = db.Column(db.Integer, default=3, comment='最大重试次数')
    
    # 环境配置
    is_sandbox = db.Column(db.Boolean, default=False, comment='是否沙箱环境')
    
    # 时间戳
    created_at = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
    updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')
    
    def __repr__(self):
        return f'<PaymentConfig {self.name}: {self.payment_method}>'
    
    def to_dict(self, include_sensitive=False):
        """转换为字典，可选择是否包含敏感信息"""
        data = {
            'id': self.id,
            'name': self.name,
            'payment_method': self.payment_method,
            'is_enabled': self.is_enabled,
            'timeout_seconds': self.timeout_seconds,
            'max_retry_times': self.max_retry_times,
            'is_sandbox': self.is_sandbox,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S') if self.created_at else None,
            'updated_at': self.updated_at.strftime('%Y-%m-%d %H:%M:%S') if self.updated_at else None
        }
        
        if include_sensitive:
            # 只有管理员才能看到敏感信息
            if self.payment_method == 'wechat':
                data.update({
                    'wechat_app_id': self.wechat_app_id,
                    'wechat_mch_id': self.wechat_mch_id,
                    'wechat_api_key': '***' if self.wechat_api_key else None,  # 隐藏密钥
                    'wechat_cert_path': self.wechat_cert_path,
                    'wechat_key_path': self.wechat_key_path,
                    'wechat_notify_url': self.wechat_notify_url
                })
            elif self.payment_method == 'alipay':
                data.update({
                    'alipay_app_id': self.alipay_app_id,
                    'alipay_private_key': '***' if self.alipay_private_key else None,
                    'alipay_public_key': '***' if self.alipay_public_key else None,
                    'alipay_notify_url': self.alipay_notify_url
                })
        else:
            # 不包含敏感信息的基本配置
            if self.payment_method == 'wechat':
                data.update({
                    'wechat_app_id': self.wechat_app_id,
                    'wechat_mch_id': self.wechat_mch_id,
                    'wechat_notify_url': self.wechat_notify_url,
                    'has_cert': bool(self.wechat_cert_path),
                    'has_key': bool(self.wechat_api_key)
                })
        
        return data
    
    def get_wechat_config(self):
        """获取微信支付配置"""
        if self.payment_method != 'wechat':
            return None
            
        return {
            'app_id': self.wechat_app_id,
            'mch_id': self.wechat_mch_id,
            'api_key': self.wechat_api_key,
            'cert_path': self.wechat_cert_path,
            'key_path': self.wechat_key_path,
            'notify_url': self.wechat_notify_url,
            'timeout': self.timeout_seconds,
            'is_sandbox': self.is_sandbox
        }
    
    @classmethod
    def get_active_wechat_config(cls):
        """获取当前激活的微信支付配置"""
        return cls.query.filter_by(
            payment_method='wechat',
            is_enabled=True
        ).first()
    
    def validate_wechat_config(self):
        """验证微信支付配置的完整性"""
        if self.payment_method != 'wechat':
            return False, "不是微信支付配置"
            
        required_fields = [
            ('wechat_app_id', '微信应用ID'),
            ('wechat_mch_id', '微信商户号'),
            ('wechat_api_key', '微信API密钥'),
            ('wechat_notify_url', '回调地址')
        ]
        
        for field, name in required_fields:
            if not getattr(self, field):
                return False, f"缺少{name}"
        
        return True, "配置完整" 